package cn.tedu._04weibo.base.exception;


import cn.tedu._04weibo.base.response.JsonResult;
import cn.tedu._04weibo.base.response.StatusCode;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(IllegalArgumentException.class)
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException ex) {
        String data=ex.getMessage();
        log.error("doHandleIllegalArgumentException: "+data);
        return JsonResult.fail(data);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        String data=ex.getFieldError().getDefaultMessage();
        log.error("doHandleMethodArgumentNotValidException: "+data);
        return JsonResult.fail(data);
    }
    @ExceptionHandler(ConstraintViolationException.class)
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException ex) {
        //String data=ex.getConstraintViolations().iterator().next().getMessage();
        String data=ex.getMessage().split(": ")[1].trim();
        log.error("doHandleConstraintViolationException: "+data);
        return new JsonResult(StatusCode.VALIDATED_ERROR,data);
    }


    @ExceptionHandler(RuntimeException.class)
    public JsonResult doHandleIllegalargumentException(IllegalArgumentException ex) {
        String data=ex.getMessage();
        log.error("doHandleRuntimeException: "+data);
        return new JsonResult(StatusCode.OPERATION_FAILED,data);
    }

}
